/**
 * ajax请求配置
 */
import axios from 'axios'
import apiURL from './api.js'
import router from '../config/router'
import { Loading, Message,Notification  } from 'element-ui'


var instance = axios.create({
  baseURL: apiURL,
  timeout: 5000,
});

var instanceImg = axios.create({
  baseURL: 'http://210.41.45.4/jxfl',
  changeOrigin: true,
  timeout: 5000,
});

// axios默认配置
instance.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
// instance.defaults.headers.common['token'] =sessionStorage.token;

// 路由请求拦截
// http request 拦截器
instance.interceptors.request.use(
    config => {
      // 判断是否存在token，如果存在的话，则每个http header都加上ticket
      if (sessionStorage.token) {
        config.headers.token = sessionStorage.token
      }else{
        router.push('/')
      }
      return config;
    },
    error => {
      return Promise.reject(error);
    });
  
  // 路由响应拦截
  // http response 拦截器
  instance.interceptors.response.use(
    response => {
      if(response.data.code == '200'){
          return response;
      }else{
        if (response.data.code == '500' ) {
          switch ( response.data.data) {
            case '密码错误':
                  router.push('/');
                  sessionStorage.removeItem('token');
                  Message.error('账号或密码错误！！');
              break;
  
            case '该用户不存在':
                  router.push('/');
                  sessionStorage.removeItem('token');
                  Message.error('账号或密码错误！！');
              break;
  
              case '请先登陆再进行其他操作':
                  router.push('/')
                  sessionStorage.removeItem('token')
                  sessionStorage.removeItem('defaultActive')
                  Message.warning('会话过期，请重新登录');
                break;
          
            default:
                console.log(response)
                Message.warning(response.data.data);
                // return response;
              break;
          }
        }else{
          router.push('/')
          Message.warning(response.data.data);
          sessionStorage.removeItem('token')
          sessionStorage.removeItem('defaultActive')
        }
      }
    }
  );

    export default instance